<template>
  <el-dialog :visible="showDialogStatus"
             width="920px"
             :top="`${comDialogTop}px`"
             class="preview-data"
             :close-on-click-modal="false"
             :modal='true'
             @close='showDialogStatus = false'
             :before-close="beforeCloseDialog"
             :title="$t('custom.dataInspector')"
             append-to-body>
    <el-tabs v-model="nowPane"
             type="border-card"
             style="height:770px;"
             tab-position="left">
      <el-tab-pane label="Raw Data"
                   name="rawData">
        <div v-loading="rawDataLoading"
             class="raw-data-content pane-item-content">
          <ejs-grid v-if="rawDataList.length > 0"
                    :dataSource="rawDataList"
                    :allowPaging="true"
                    :width='709'
                    :allowResizing='true'
                    :pageSettings="pageSettings"
                    :dataBound="dataBound"
                    ref="rawdata-grid"></ejs-grid>
          <div class="preview-rawdata-nodata"
               v-else>
            <img :src="$ossLink+'/app/gadget/gadget_no_data.jpg'">
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="SQL"
                   v-if="$hasPermission('sys:preview:data:debugger')"
                   name="sql">
        <div v-loading="otherDataLoading"
             class="pane-item-content">
          <div class="custom-card">
            <div class="custom-card-header">
              <div>Raw SQL</div>
              <div class="cuifont icon_copy1"
                   @click="copyValue(rawSql)"></div>
            </div>
            <BMonacoEditor
              v-model="rawSql"
              :editable="true" 
              :height="250"          
             />
            <!-- <div class="custom-card-content scroll-css">{{ rawSql }}</div> -->
          </div>
          <div class="custom-card">
            <div class="custom-card-header">
              <div>{{$t('custom.component.previewData.executeSql')}}</div>
              <div class="cuifont icon_copy1"
                   @click="copyValue(executeSql)"></div>
            </div>
            <BMonacoEditor
              v-model="executeSql"
              :editable="true" 
              :height="250"          
             />
            <!-- <div class="custom-card-content scroll-css">{{ executeSql }}</div> -->
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('custom.component.previewData.fieldDescription')"
                   v-if="$hasPermission('sys:preview:data:debugger')"
                   name="fieldDescription">
        <div v-loading="otherDataLoading"
             class="pane-item-content">
          <div class="custom-card">
            <div class="custom-card-header">
              <div>{{$t('custom.component.previewData.fieldDescription')}}</div>
              <div class="cuifont icon_copy1"
                   @click="copyValue(fieldDescription)"></div>
            </div>
            <div class="custom-card-content scroll-css">{{ fieldDescription }}</div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('custom.component.previewData.query')"
                   v-if="$hasPermission('sys:preview:data:debugger')"
                   name="query">
        <div v-loading="otherDataLoading"
             class="pane-item-content">
          <div class="custom-card">
            <div class="custom-card-header">
              <div>{{$t('custom.component.previewData.query')}}</div>
              <div class="cuifont icon_copy1"
                   @click="copyValue(query)"></div>
            </div>
            <div class="custom-card-content scroll-css">{{ query }}</div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="Error Log"
                   v-if="$hasPermission('sys:preview:data:debugger')"
                   name="errorLog">
        <div v-loading="otherDataLoading"
             class="pane-item-content">
          <div class="custom-card">
            <div class="custom-card-header">
              <div>{{$t('custom.component.previewData.errorLog')}}</div>
              <div class="cuifont icon_copy1"
                   @click="copyValue(errorLog)"></div>
            </div>
            <div class="custom-card-content scroll-css">{{ errorLog }}</div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script>
import { generalConvertJsonToSQL, getUrlQureyParams } from '@/utils/common'
import BMonacoEditor from '@/components/storybook/b-monaco-editor/index.vue'

export default {
  components: {
    BMonacoEditor
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    datasetId: {
      type: String,
      default: null
    },
    gadgetId: {
      type: String,
      default: null
    },
    filterJson: {
      type: Object,
      default: () => {
        return {}
      }
    },
    datasetLayerId: {
      type: String,
      default: null
    }
  },
  data () {
    return {
      showDialogStatus: false,
      rawDataLoading: false,
      otherDataLoading: false,
      pageSettings: { pageSize: 10, pageSizes: [10, 50, 100, 200, 1000], pageCount: 1 },
      rawDataList: [],
      rawSql: null,
      executeSql: null,
      fieldDescription: null,
      query: null,
      errorLog: null,
      nowPane: 'rawData',
      isGridInit: false
    }
  },
  computed: {
    comDialogTop () {
      return window.innerHeight > 824 ? (window.innerHeight - 824) / 2 : 20
    },
    comFilter () {
      if (Object.keys(this.filterJson).length > 0) {
        return generalConvertJsonToSQL(this.filterJson)
      } else {
        return ''
      }
    }
  },
  methods: {
    init () {
      if (this.datasetId || this.datasetLayerId || this.gadgetId) {
        this.showDialogStatus = true
        if (this.datasetId && this.gadgetId) {
          this.gadgetId = null
        }
        this.getDataList()
        this.$hasPermission('sys:preview:data:debugger') && this.getOtherData()
      } else {
        this.$message.warning('Origin data is null')
      }
    },
    getDataList () {
      this.rawDataLoading = true
      let params = {
        filter: this.comFilter
      }
      this.datasetId && (params['datasetId'] = this.datasetId)
      this.gadgetId && (params['gadgetId'] = this.gadgetId)
      this.datasetLayerId && (params['datasetLayerId'] = this.datasetLayerId)
      let botid = getUrlQureyParams('botId')
      if (botid) {
        params['botId'] = botid
      }
      this.$interface.reports.postInfoForGetDataApi(params)
        .then(({ data: res }) => {
          this.rawDataLoading = false
          this.errorLog = res.msg
          this.rawDataList = res.data
          this.isGridInit = false
        }).catch(() => {
          this.rawDataLoading = false
        })
    },
    getOtherData () {
      this.otherDataLoading = true
      const params = {
        filter: this.comFilter,
        showSql: true,
        showQuery: true
      }
      this.datasetId && (params['datasetId'] = this.datasetId)
      this.gadgetId && (params['gadgetId'] = this.gadgetId)
      this.datasetLayerId && (params['datasetLayerId'] = this.datasetLayerId)
      this.$interface.reports.checkSql(params)
        .then(({ data: res }) => {
          this.otherDataLoading = false
          this.rawSql = res.rawSql
          this.executeSql = res.executeSql
          this.query = JSON.stringify(res.query)
          this.fieldDescription = JSON.stringify(res.data)
        }).catch(() => {
          this.otherDataLoading = false
        })
    },
    copyValue (val) {
      if (!val) {
        return this.$message.error('No Data!')
      }
      const oInput = document.createElement('textarea')
      document.body.appendChild(oInput)
      oInput.value = val
      oInput.select()
      document.execCommand('Copy')
      oInput.remove()
      this.$message.success('Copied.')
    },
    beforeCloseDialog () {
      Object.assign(this.$data, this.$options.data())
    },
    dataBound (args) {
      if (!this.isGridInit) {
        this.isGridInit = true
        let _self = this
        if (_self.$refs['rawdata-grid']) {
          let gridConfig = JSON.parse(_self.$refs['rawdata-grid'].ej2Instances.getPersistData())
          if (gridConfig && gridConfig.columns.length > 0) {
            for (let i = 0; i < gridConfig.columns.length; i++) {
              gridConfig.columns[i]['autoFit'] = true
            }
            _self.$refs['rawdata-grid'].ej2Instances.setProperties(gridConfig)
          }
        }
      }
    }
  }
}
</script>

<style lang="scss">
.preview-data {
  .el-dialog__header {
    padding: 13px 20px 15px 20px;
    border: 1px solid transparent;
  }
  .el-dialog__body {
    padding: 0;
  }
  .el-tabs--border-card > .el-tabs__header {
    background-color: #fff;
  }
  .el-tabs--left .el-tabs__header.is-left {
    margin-right: 0;
  }
  .el-tabs--left.el-tabs--border-card .el-tabs__item.is-left.is-active {
    border-color: transparent;
    border-right: 2px solid $--theme-color;
    background-color: $--theme-color-background;
    color: $--theme-color;
  }
  .el-tabs--left.el-tabs--border-card .el-tabs__item.is-left {
    width: 170px;
    height: 56px;
    line-height: 56px;
    font-size: 14px;
    text-align: left;
  }
  .el-tabs--border-card > .el-tabs__content {
    padding: 20px;
  }
  // .e-grid .e-headercelldiv {
  //   text-align: center;
  // }
  // .e-grid .e-table {
  //   width: auto;
  // }
  .e-grid .e-gridcontent {
    height: 620px;
    .e-content {
      height: 620px !important;
    }
  }
  .e-grid .e-pager {
    height: 60px;
  }
  .pane-item-content {
    width: 100%;
    height: 730px;
    overflow-x: auto;
    .custom-card {
      width: 710px;
      height: 300px;
      background: #f0f0f0;
      border-radius: 6px;
      margin-bottom: 10px;
      padding: 10px;
      &:last-child {
        margin-bottom: 0;
      }
      &-header {
        width: 100%;
        height: 28px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: bold;
        .cuifont {
          cursor: pointer;
          font-size: 14px;
          &:hover {
            color: $--theme-color;
          }
        }
      }
      &-content {
        width: 690px;
        height: 242px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #f0f0f0;
        padding: 10px;
        margin-top: 10px;
        color: #404040;
        line-height: 20px;
      }
    }
  }
  .raw-data-content {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .preview-rawdata-nodata {
    width: 350px;
    height: 242px;
    img {
      filter: invert(0%);
      width: 100%;
      height: 100%;
    }
  }
}
</style>
